﻿using System;
using System.Text;
using CustomerContactSystem.Core.Model;

namespace CustomerContactSystem.WebForms.Enquiries {
    public partial class Delete : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id,from")) {
                return;
            }

            if (Request.QueryString["from"] == "search") {
                CancelDeleteLink.NavigateUrl = "~/Enquiries/Search.aspx?" + GetQueryString();
            }
            else {
                CancelDeleteLink.NavigateUrl = "~/Enquiries/Search.aspx";
            }

            EnquiryId.Text = Request.QueryString["id"];
        }

        protected void DeleteEnquiryClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id,from")) {
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            int duplicateId;
            int.TryParse(DuplicateEnquiryId.Text, out duplicateId);

            var enquiryDeletion = new EnquiryDeletion
                {
                    DateOfDeletion = DateTime.Now,
                    DuplicateOfEnquiryId = duplicateId,
                    ReasonForDeletion = ReasonForDeletion.Text
                };

            if (!IsValidObject(enquiryDeletion, DeleteEnquiryResultMessage)) {
                return;
            }

            EnquiryDeletionRepository.Add(enquiryDeletion);

            var enquiry = EnquiryRepository.GetById(enquiryId);
            enquiry.Delete(LoggedUser.DisplayName, enquiryDeletion);

            EnquiryRepository.Update(enquiry);

            if (Request.QueryString["from"] == "search") {
                Response.Redirect("~/Enquiries/Search.aspx?" + GetQueryString());
            } else {
                Response.Redirect("~/Enquiries/Search.aspx");
            }
        }

        private string GetQueryString() {
            var sb = new StringBuilder();
            foreach (var qryKey in Request.QueryString.Keys) {
                if (qryKey.ToString() != "id" && qryKey.ToString() != "from") {
                    sb.Append("&" + qryKey + "=" + Request.QueryString[qryKey.ToString()]);
                }
            }
            return sb.ToString().Trim('&');
        }
    }
}